package com.sgb.kjwl.viewmodel.self.packers;

import android.util.Log;

import com.alibaba.sdk.android.vod.upload.VODUploadCallback;
import com.alibaba.sdk.android.vod.upload.VODUploadClient;
import com.alibaba.sdk.android.vod.upload.VODUploadClientImpl;
import com.alibaba.sdk.android.vod.upload.model.UploadFileInfo;
import com.alibaba.sdk.android.vod.upload.model.VodInfo;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.swgk.core.view.entity.AliProofEntity;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.self.SelfTeamDeviceEntity;
import com.sgb.kjwl.repository.SelfRepertory;
import com.sgb.kjwl.utils.GlideEngine;
import com.sgb.kjwl.view.ui.activity.self.packers.SelfTeamDeviceEditActivity;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SelfTeamDeviceEditModel extends BaseViewModel {
    private SelfTeamDeviceEditActivity mActivity;

    public SelfTeamDeviceEditModel(SelfTeamDeviceEditActivity activity, SelfRepertory repertory) {
        mActivity = activity;
    }

    public void detailEquipment(String no) {
        Map<String,Object> map = new HashMap<>();
        map.put("no",no);
        DialogHelper.showProgressDialog(mActivity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getTeamNewInterfaceAPI().detailEquipment(map).enqueue(new Callback<BaseEntity<SelfTeamDeviceEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<SelfTeamDeviceEntity>> call, Response<BaseEntity<SelfTeamDeviceEntity>> response) {
                DialogHelper.dismissProgressDialog();
                BaseEntity<SelfTeamDeviceEntity> body = response.body();
                if (body == null || body.getState() == null) {
                    mActivity.showEmpty();
                    return;
                }
                if (body.getState().equals(AppConstant.REQEUST_SECCUESS)) {
                    mActivity.updateEntity(body.getData());
                } else {
                    MToast.showToast(mActivity, body.getMsg());
                    mActivity.showEmpty();
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<SelfTeamDeviceEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(mActivity, t.getMessage());
                mActivity.showEmpty();
            }
        });
    }

    public void addEquipment(SelfTeamDeviceEntity entity) {
        DialogHelper.showProgressDialog(mActivity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().addEquipment(entity).enqueue(new Callback<BaseEntity<Object>>() {
            @Override
            public void onResponse(Call<BaseEntity<Object>> call, Response<BaseEntity<Object>> response) {
                DialogHelper.dismissProgressDialog();
                BaseEntity<Object> body = response.body();
                if (body == null || body.getState() == null) {
                    MToast.showToast(mActivity, "发布失败！");
                    return;
                }
                if (body.getState().equals(AppConstant.REQEUST_SECCUESS)) {
                    mActivity.editEntitySuccess();
                } else {
                    MToast.showToast(mActivity, body.getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<Object>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(mActivity, "发布失败！");
            }
        });
    }

    //上传视频
    private VODUploadClient mUploadClient;

    public void pictureSelector(int number) {
        PictureSelector.create(mActivity)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)
                .selectionMode(PictureConfig.MULTIPLE)
                .compress(true)//是否压缩
                .minimumCompressSize(10240)//小于10M不压缩
                .maxSelectNum(number)//判断还能选多少张图片
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    /**
     * 上传多图片
     * @param file
     * @param completeNum
     * @param imgTotal
     * @param isDevice
     */
    public void uploadMultiFileModel(File file, int completeNum, int imgTotal, boolean isDevice) {
        Map<String, RequestBody> photos = new HashMap<>();
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        photos.put("file" + "\"; filename=\"" + completeNum + "image.jpg\"", requestBody);
        DialogHelper.showProgressDialog(mActivity, null, "图片上传中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUploadAPI().uploadFile(photos).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    mActivity.uploadPicInfo(file.getAbsolutePath(), response.body().getData().toString(), isDevice);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(mActivity, t.getMessage());
            }
        });
    }

    public void videoSelector(int number) {
        PictureSelector.create(mActivity)
                .openGallery(PictureMimeType.ofVideo())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)
                .selectionMode(PictureConfig.SINGLE)
                .maxSelectNum(number)
                .forResult(PictureConfig.TYPE_VIDEO);
    }

    private AliProofEntity mProofEntity;

    /**
     * 添加文件，获取上传凭证
     * @param path
     */
    public void uploadVideo(String path) {
        VodInfo vodInfo = new VodInfo();
        vodInfo.setTitle("视频");
        vodInfo.setDesc("自有设备视频.");
        vodInfo.setCateId((int) System.currentTimeMillis());
        vodInfo.setTags(null);
        if (mUploadClient == null) {
            mUploadClient = new VODUploadClientImpl(mActivity.getApplicationContext());
        }
        mUploadClient.addFile(path, vodInfo);
        // 获取上传凭证
        DialogHelper.showProgressDialog(mActivity, null, "上传视频中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getSelfGoodsPublishAPI().getVideoParams().enqueue(new Callback<BaseEntity<AliProofEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<AliProofEntity>> call, Response<BaseEntity<AliProofEntity>> response) {
                if ("ok".equals(response.body().getState())) {
                    mProofEntity = response.body().getData();
                    //阿里凭证
                    mUploadClient.init(mUploadCallback);
                    mUploadClient.start();
                } else {
                    DialogHelper.dismissProgressDialog();
                    MToast.showToast(mActivity, "上传视频失败！");
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<AliProofEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MLog.d(AppConstant.API_LOG, "error " + t.getMessage());
            }
        });
    }

    VODUploadCallback mUploadCallback = new VODUploadCallback() {
        @Override
        public void onUploadSucceed(UploadFileInfo info) {
            Log.e("onUploadSucceed", "onUploadSucceed");
            mActivity.updateVideoInfo(mProofEntity.getVideoId(), info.getFilePath());
            DialogHelper.dismissProgressDialog();
        }

        @Override
        public void onUploadFailed(UploadFileInfo info, String code, String message) {
            Log.e("onUploadFailed", "onUploadFailed");
        }

        @Override
        public void onUploadProgress(UploadFileInfo info, long uploadedSize, long totalSize) {
            Log.e("onUploadFailed", "onUploadFailed");
        }

        @Override
        public void onUploadTokenExpired() {
            Log.e("onUploadTokenExpired", "onUploadTokenExpired");
            mUploadClient.resumeWithAuth(mProofEntity.getUploadAuth());
        }

        @Override
        public void onUploadRetry(String code, String message) {
            Log.e("onUploadRetry", "onUploadRetry");
        }

        @Override
        public void onUploadRetryResume() {
            Log.e("onUploadRetryResume", "onUploadRetryResume");
        }

        @Override
        public void onUploadStarted(UploadFileInfo uploadFileInfo) {
            Log.e("onUploadStarted", "onUploadStarted");
            mUploadClient.setUploadAuthAndAddress(uploadFileInfo, mProofEntity.getUploadAuth(), mProofEntity.getUploadAddress());
        }
    };

    public void getEquipmentConfig() {
        DialogHelper.showProgressDialog(mActivity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().getEquipmentConfig().enqueue(new Callback<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity>>> call, Response<BaseEntity<List<PickSelectEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    List<PickSelectEntity> data = response.body().getData();
                    if (data == null || data.size() == 0) {
                        data = new ArrayList<>();
                    }
                    mActivity.showEquipmentConfigPop(data);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

}
